import axios from 'axios'
// import qs from 'qs'

axios.interceptors.request.use(config => {
  // loading
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

const plugin = {}

plugin.install = function (Vue, options) {
  const request = (api, data0 = {}) => {
    return new Promise((resolve, reject) => {
      // 拼接请求url
      const url = api.url
      // method必须为大写
      const method = (api.method).toUpperCase()
      // 自定义请求头部
      let headers = options.header
      if (typeof (headers) === 'function') {
        headers = headers()
      }
      axios({
        method,
        url,
        data: JSON.stringify(data0),
        timeout: 10000,
        headers
      }).then(
        (response) => {
          const { status, data } = response
          if (status === 200) {
            resolve(data)
          } else {
            resolve({
              code: 0,
              msg: '请求失败'
            })
          }
        }
      ).then(
        (res) => {
          if (res) { console.log(res) }
        }
      )
    })
  }

  Vue.prototype.$request = request
}

export default plugin
